import const
import GameWorld
import movement
import uthread

class MovementClient(movement.movementService):
    __guid__ = 'svc.movementClient'
    __dependencies__ = ['machoNet']
    __notifyevents__ = ['ProcessEntityMove', 'OnSessionChanged']
    __componentTypes__ = ['movement']
    reportedMissing = False
    TIME_BEFORE_SENDING = ((6 * const.SEC) / 30)

    def Run(self, *etc):
        self.lastSentTime = 0
        self.unsentPlayerMoves = []
        self.movementServer = sm.RemoteSvc('movementServer')
        self.addressCache = {}
        self.movementChannel = self.machoNet.GetGPCS('movement')
        GameWorld.Manager.processEntityMoveFunc = self.ProcessEntityMove
        GameWorld.Manager.sendToServerFunc = self.SendMovePlayerToServer



    def OnSessionChanged(self, isRemote, sess, change):
        newworldspaceid = change.get('worldspaceid', (None, None))[1]
        self.LookupWorldSpaceNodeID(newworldspaceid)



    def LookupWorldSpaceNodeID(self, newworldspaceid):
        if (newworldspaceid and (newworldspaceid not in self.addressCache)):
            nodeid = self.movementServer.ResolveNodeID(newworldspaceid)
            if nodeid:
                self.addressCache[newworldspaceid] = nodeid
            else:
                self.LogError('Trying to resolve a unknown worldspaceid to a node', newworldspaceid)
        return self.addressCache.get(newworldspaceid, None)



    def GetPlayerEntity(self):
        raise StandardError('Not implemented')



    def GetEntity(self, entid):
        raise StandardError('Not implemented')



    def GetEntityMovement(self, ent):
        raise StandardError('Not implemented')



    def SendMovePlayer(self, move):
        nodeID = self.addressCache.get(session.worldspaceid, None)
        if not nodeID:
            uthread.new(self.LookupWorldSpaceNodeID, session.worldspaceid)
        if nodeID:
            self.movementChannel.SendMovementToServer(move, nodeID)
        else:
            self.LogWarn('Delaying sending movement, since I have no idea where to send it to')



    def IsPlayerEntity(self, entity):
        raise StandardError('Not implemented')



    def SendMovePlayerToServer(self, *move):
        self.SendMovePlayer(move)




